import config from './config.js'
import store from '@/store/index.js'
import Axios from 'axios'
let wx = require('weixin-js-sdk')

export default {
  ajax: function (p) {
    let obj = {
      cbSuccess: function () {},
      cbError: function () {},
      method: 'post',
      path: '',
      data: {},
      header: {},
      showLoading: function () {},
      hideLoading: function () {}
    }
    store.dispatch('getAuth')
    obj.header.Authorization = 'Bearer ' + store.getters.auth('jwt')

    Object.assign(obj, p)
    obj.showLoading()

    let that = this
    Axios({
      url: config.apiURI + obj.path,
      method: obj.method,
      data: obj.data,
      headers: obj.header
    }).then(function (res) {
      let data = res.data
      if (data.status === 200) {
        obj.cbSuccess(data)
      } else if (data.status === 400) {
        if (data.msg !== 'auth_timeout') {
          let authErrors = ['auth_empty', 'auth_error', 'auth_refresh_error']
          if (authErrors.indexOf(data.msg) >= 0) {
            store.dispatch('loginOut')
            store.dispatch('loginNeed')
          }
          obj.cbError(data)
        } else {
          that.refreshJwt(p)
        }
      } else {
        obj.cbError({msg: 'unknown_error'})
      }
      obj.hideLoading()
    }).catch(function (error) {
      obj.hideLoading()
      obj.cbError({msg: 'net_error'})
      console.log(error)
    })
  },
  refreshJwt: function (p) {
    let uinfo = store.getters.auth('jwtRef')
    if (uinfo === null) {
      store.dispatch('loginOut')
      store.dispatch('loginNeed')
      return false
    }
    let that = this
    that.ajax({
      path: config.refreshJwt,
      method: 'get',
      header: {
        'Authorization': 'Bearer ' + uinfo
      },
      cbSuccess: function (res) {
        store.dispatch('updateAuth', {jwt: res.memo.jwt, jwtRef: res.memo.jwt_refresh})
        that.ajax(p)
      },
      cbError: function () {
        store.dispatch('loginOut')
        store.dispatch('loginNeed')
      }
    })
  },
  verify: {
    check: function (vdata) {
      for (let d in vdata) {
        let v = vdata[d]
        for (let r in v.rules) {
          let rdata = v.rules[r]
          if (this.rules['_' + r](v.val, rdata.args) === false) {
            return rdata.msg
          }
        }
      }
      return true
    },
    rules: {
      _required: function (val) {
        if (val !== '') {
          return true
        }
        return false
      },
      _nochinese: function (val) {
        let p = /^[^\u4e00-\u9fa5]{0,}$/
        return p.test(val)
      },
      _email: function (val) {
        let p = /^[a-zA-Z0-9._%+-]+@(?!.*\.\..*)[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/
        return p.test(val)
      },
      _mobile: function (val) {
        let p = /^(13|14|15|16|17|18|19)\d{9}$/
        return p.test(val)
      },
      _alphanumeric: function (val) {
        let p = /^\w+$/
        return p.test(val)
      },
      _digits: function (val) {
        let p = /^[-,+]?\d+$/
        return p.test(val)
      },
      _number: function (val) {
        let p = /^[-,+]?\d+(\.\d+)?$/
        return p.test(val)
      },
      _integerNumber: function (val) {
        let p = /^[1-9]+\d*$/
        return p.test(val)
      },
      _equalTo: function (val, args) {
        if (val === args[0]) {
          return true
        }
        return false
      },
      _rangeLength: function (val, args) {
        if (val.length <= args[1] && val.length >= args[0]) {
          return true
        }
        return false
      },
      _equalLength: function (val, args) {
        if (val.length === args[0]) {
          return true
        }
        return false
      },
      _maxLength: function (val, args) {
        if (val.length <= args[0]) {
          return true
        }
        return false
      },
      _minLength: function (val, args) {
        if (val.length >= args[0]) {
          return true
        }
        return false
      },
      _date: function (val) {
        let p = /^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/
        return p.test(val)
      }
    },
    addRule: function (name, fn) {
      this.rules['_' + name] = fn
    }
  },
  formatDate: function (odate, format) {
    odate = odate.replace(/-/g, '/')
    let myDate = new Date(odate)
    let m = myDate.getMonth() + 1
    let d = myDate.getDate()
    let h = myDate.getHours()
    let i = myDate.getMinutes()
    let s = myDate.getSeconds()
    format = format.replace('yyyy', myDate.getFullYear())
    format = format.replace('mm', m < 10 ? ('0' + m) : m)
    format = format.replace('dd', d < 10 ? ('0' + d) : d)
    format = format.replace('hh', h < 10 ? ('0' + h) : h)
    format = format.replace('ii', i < 10 ? ('0' + i) : i)
    format = format.replace('ss', s < 10 ? ('0' + s) : s)
    return format
  },
  shareURI () {
    let shareWxLink = config.apiURI + 'Interfaces/shareurl/?url='
    let url = window.location.href.split('#/')
    shareWxLink += url[1] ? encodeURIComponent(url[1]) : ''
    return shareWxLink
  },
  getShare (title) {
    let ua = navigator.userAgent.toLowerCase()
    console.log(title)
    let that = this
    if (ua.indexOf('micromessenger') > -1) {
      that.ajax({
        path: 'interfaces/jssdksign',
        method: 'post',
        data: {
          url: location.href.split('#')[0]
        },
        cbSuccess (data) {
          that.begin(data.memo.nonceStr, data.memo.signature, data.memo.timestamp, title)
        },
        cbError (error) {
          console.log(error)
        }
      })
    }
  },
  // 微信分享
  begin (nonceStr, signature, timestamp, title) {
    // let that = this
    let shareWxLink = this.shareURI()
    wx.config({
      debug: false,
      appId: 'wx4999af4af069bec3',
      timestamp: timestamp,
      nonceStr: nonceStr,
      signature: signature,
      jsApiList: ['updateAppMessageShareData', 'updateTimelineShareData', 'onMenuShareTimeline', 'onMenuShareAppMessage']
    })
    wx.ready(function () {
      // alert('开始')
      wx.updateAppMessageShareData({
        title: title, // 分享标题
        desc: '侃侃网-跨境电商一站式新媒体平台', // 分享描述
        link: shareWxLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: config.webUrl + 'img/xiaolg.png', // 分享图标
        success: function () {
          // 设置成功
          //   alert('分享给朋友,分享到QQ,设置成功')
        }
      })
      wx.updateTimelineShareData({
        title: title, // 分享标题
        link: shareWxLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
        imgUrl: config.webUrl + 'img/xiaolg.png', // 分享图标
        success: function () {
          // 设置成功
          // alert('分享到朋友圈,分享到QQ空间,设置成功')
        }
      })
    })
    wx.onMenuShareTimeline({
      title: title, // 分享标题
      link: shareWxLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: config.webUrl + 'img/xiaolg.png', // 分享图标
      success: function () {
        // 用户点击了分享后执行的回调函数
      }
    })
    wx.onMenuShareAppMessage({
      title: title, // 分享标题
      desc: '侃侃网-跨境电商一站式新媒体平台', // 分享描述
      link: shareWxLink, // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
      imgUrl: config.webUrl + 'img/xiaolg.png', // 分享图标
      type: '', // 分享类型,music、video或link，不填默认为link
      dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
      success: function () {
        // 用户点击了分享后执行的回调函数
      }
    })
    wx.error(function (res) {
      console.log(res)
    })
  }
}
